﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using LevenBlog.Core.Data;
using LevenBlog.Core.Entities;
using LevenBlog.Core.Service;
using LevenBlog.Core.Cache;
using LevenBlog.Core.User;

namespace LevenBlog.Core.Mvc
{
    public abstract class BaseController : Controller
    {
        private IDbProvider provider = null;

        private IMembership membership = null;

        protected readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(BaseController));

        protected string title
        {
            get { return ViewData["title"] == null ? string.Empty : ViewData["title"].ToString(); }
            set { ViewData["title"] = value; }
        }

        public BaseController()
        {
            ViewData["starttime"] = DateTime.Now;
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile));
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            Logger.Error("系统出现未处理错误:", filterContext.Exception);
            base.OnException(filterContext);
        }

        protected IDbProvider Provider
        {
            get
            {
                if (provider == null)
                {
                    provider = ProviderManager.Factory.CreateDbProvider();
                    provider.Open();
                }
                return provider;
            }
        }

        public virtual IMembership Membership
        {
            get
            {
                if (membership == null)
                {
                    membership = new UserMembership(Provider);
                    membership.Read();
                }
                return membership;
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (provider != null)
                provider.Dispose();
            base.Dispose(disposing);
        }
    }
}
